package com.czkt.conflg;


import com.czkt.pojo.Vo.UserRoleMenuVo;
import com.czkt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;


import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import reactor.util.annotation.Nullable;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    CustoUserDeatailService custoUserDeatailService;
    @Autowired
    UserService userService;
    @Autowired
    MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception {

        UserRoleMenuVo userRoleMenuVo = userService.userRoleMenu("text");
        System.out.println("角色："+userRoleMenuVo.getRole().getRoleName());
        System.out.println("权限："+userRoleMenuVo.getMenu().getMenuName());
        return security.formLogin(formobin -> formobin
                        //自定义登录页面
//                        .successHandler(myAuthenticationSuccessHandler)
                        .permitAll())
                .authorizeHttpRequests(authori -> authori
                        //.mvcMatchers("booksClass/list")只有设置的用户才可以访问这个路径
                        // .hasAuthority("admin")只有设置的用户才可以访问
                        .mvcMatchers(userRoleMenuVo.getMenu().getMenuName()).hasRole(userRoleMenuVo.getRole().getRoleName())
                        .anyRequest().authenticated()
                )
                .userDetailsService(custoUserDeatailService)
                .build();

    }
}
